<?php

namespace App\Plugin\HostServer\Middleware;

use App\Plugin\Forum\Front\AuthController;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\URL;

class UserAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $guard = 'host_server';

        if (Auth::guard($guard)->guest()) {

            return $this->authCheck('login',$request);;
        } else {
            //判断是否被禁用
            $user = Auth::guard($guard)->user();

            if ($user['is_checked'] == 0) {
                Auth::guard($guard)->logout();
                $request->session()->invalidate();
                return $this->authCheck('checked',$request);

            } else {
                //判断session是否跟登录的一致
               /* if(!cache('last_session')){

                    cache()->forever('last_session',$user['session_token']);
                }
                $session_id=cache('last_session');
                dump($session_id);
                echo $user['email'];
                echo $user['session_token'];
                if ($session_id != $user['session_token']) {
                    Auth::guard('forum')->logout();
                    $request->session()->invalidate();
                    return $this->authCheck('other_login',$request);
                }*/

            }
        }

        return $next($request);
    }

    public function authCheck($type = '', $request)
    {
        $json_data = ['code' => 1000, 'msg' => '请登陆后操作', 'url' => route('plugin.hostserver.login')];
        if ($type == 'checked') {
            $json_data = ['code' => 401, 'msg' => '账号被禁用', 'url' => route('plugin.hostserver.login')];
        } elseif ($type == 'other_login') {
            $json_data = ['code' => 401, 'msg' => '您的账号在另外一个地方登录了', 'url' => route('plugin.hostserver.login')];
        }
        if ($request->ajax() || $request->wantsJson()) {
            return response()->json($json_data);
        } else {
            if ($type == 'login') {
                return redirect()->route('plugin.hostserver.login');
            } else {
                return response()->view('plugin.layout.error', $json_data);

            }

        }
    }
}